package com.lagou.task.servlet;

import com.lagou.task.service.AdminService;
import com.lagou.task.entity.Admin;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("adminName");
        String password = request.getParameter("password");
        // 获取记住我框
        String remember = request.getParameter("remember");
        AdminService adminService = new AdminService();
        Admin admin = adminService.adminLoginService(new Admin(name, password));
        if (null != admin){
            System.out.println("登陆成功！");
            // 将登录成功的用户信息放入session对象中
            request.getSession().setAttribute("admin", admin);
            // 是否在浏览器记录账号
            if (remember != null){
                // 创建cookie
                Cookie cookie1 = new Cookie("adminName",admin.getName());
                Cookie cookie2 = new Cookie("password",admin.getPassword());
                cookie1.setMaxAge(60*60*24*7);
                cookie2.setMaxAge(60*60*24*7);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 实现客户端跳转
            response.sendRedirect("list");
        }else {
            System.out.println("登陆失败！");
            request.setAttribute("loginError", "loginError");
            // 实现服务器跳转  共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
